<template>
  <el-main v-loading="menu.pending.value">
    <!-- <div class="">system-menu-key</div>
    <div class="">{{ useRoute().params.key }}</div> -->

    <el-result
      v-if="menu.error.value"
      icon="error"
      title="错误"
      :sub-title="menu.error.value.message"
    >
      <template #extra>
        <el-button type="" @click="router.back()">返回</el-button>
      </template>
    </el-result>
    <!-- {{ menu.data.value }} -->
    <el-form
      v-else-if="menu.data.value"
      :model="menu.data.value"
      ref="formRef"
      :rules="rules"
      label-suffix="："
      label-width="80px"
      :label-position="isMobile ? 'top' : 'right'"
    >
      <el-form-item label="编码" prop="key">
        <el-input
          :disabled="props.type === 'edit'"
          v-model="menu.data.value.key"
        ></el-input>
      </el-form-item>
      <el-form-item label="父级" prop="parent">
        <!-- <el-tree-select
          v-model="value"
          :data="data"
          :render-after-expand="false"
        /> -->
        <menu-tree-select
          v-model="menu.data.value.parent"
          :props-disabled="propsDisabled"
          clearable
          check-strictly
          :expand-on-click-node="false"
          auto-expand-parent
          default-expand-all
          placeholder="选择父级菜单"
        ></menu-tree-select>

        <!-- <el-input v-model="menu.data.value.parent"></el-input> -->
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input v-model="menu.data.value.title"></el-input>
      </el-form-item>
      <el-form-item label="路径" prop="path">
        <el-input v-model="menu.data.value.path"></el-input>
      </el-form-item>
      <el-form-item label="图标" prop="icon">
        <icon-select v-model="menu.data.value.icon"></icon-select>
        <!-- <el-input v-model="menu.data.value.icon"></el-input> -->
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-radio-group v-model="menu.data.value.type">
          <el-radio
            v-for="item in [
              { key: MenuType.subMenu, title: '目录' },
              { key: MenuType.group, title: '分组' },
              { key: MenuType.page, title: '页面' },
            ]"
            :key="item.key"
            :label="item.key"
            >{{ item.title }}</el-radio
          >
        </el-radio-group>
        <!-- <el-input v-model="menu.data.value.type"></el-input> -->
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-switch
          v-model="menu.data.value.status"
          :active-value="Status.enable"
          :inactive-value="Status.disable"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="" @click="router.back()">取消</el-button>
        <el-button
          type="primary"
          :loading="submitMenu.pending.value"
          @click="onSubmit()"
          >保存</el-button
        >
      </el-form-item>
    </el-form>
  </el-main>
</template>

<script setup lang="ts">
import { MenuType, Menu } from '~~/types/menu.d';
import { Status } from '~~/types/status.d';
import type { FormInstance, FormRules } from 'element-plus';

const isMobile = useMediaQuery('(max-width: 425px)');
const props = defineProps({
  // key: {
  //   type: String,
  // },
  type: {
    type: String,
    default: 'edit',
  },
});
definePageMeta({
  // name: 'drawer',
  props: true,
});

const router = useRouter();
const route = useRoute();

const menu = useFetchApi(`/system/menu/${route.params.key}`, {
  default: (): Menu => ({
    key: '',
    parent: '',
    title: '',
    path: '',
    icon: '',
    type: MenuType.subMenu,
    status: 0,
    sort: 1,
  }),
  immediate: props.type === 'edit',
});
// watchAsyncDataError(menu);

if (props.type === 'add') {
  menu.data.value = {
    key: '',
    parent: '',
    title: '',
    path: '',
    icon: '',
    type: MenuType.subMenu,
    status: Status.enable,
    sort: 1,
  };
  menu.pending.value = false;
}

// const form = ref(null);

const rules = reactive<FormRules>({
  key: [{ required: true, message: '请输入编码' }],
  title: [{ required: true, message: '请输入标题' }],
  path: [],
  icon: [],
  type: [],
  status: [],
});

// const submitMenu = useFetchApi(
//   props.type === 'edit' ? `/system/menu/${route.params.key}` : '/system/menu',
//   {
//     key:
//       props.type === 'edit'
//         ? `update-system-menu-${route.params.key}`
//         : `add-system-menu`,
//     method: props.type === 'edit' ? 'put' : 'post',
//     body: menu.data,
//     immediate: false,
//   },
// );

const submitMenu = useAsyncData(
  props.type === 'edit'
    ? `update-system-menu-${route.params.key}`
    : `add-system-menu`,
  () => {
    return $fetchApi(
      props.type === 'edit'
        ? `/system/menu/${route.params.key}`
        : '/system/menu',
      {
        method: props.type === 'edit' ? 'put' : 'post',
        body: menu.data.value,
      },
    );
  },
  {
    immediate: false,
  },
);

submitMenu.pending.value = false;
watchAsyncDataError(submitMenu);

const formRef = ref<FormInstance>();

async function onSubmit() {
  if (!formRef.value) return;
  await formRef.value.validate().then(
    async () => {
      await submitMenu.execute();
      if (submitMenu.error.value) {
        // throw submitMenu.error.value;
        return;
      }
      router.back();
    },
    () => {},
  );
}

function propsDisabled(data, node) {
  // return data.key === menu.data.value?.key
  // console.log(
  //   '🚀 ~ file: [key].vue:149 ~ propsDisabled ~ data, node:',
  //   data.key,
  //   node,
  // );
  // return false

  if (!node) {
    return false;
  }
  // return false
  // 将自己与自己的子集禁用，避免形成无限循环
  function getDisabled(node) {
    if (node?.data.key === menu.data.value?.key) {
      return true;
    }
    if (node?.parent) {
      return getDisabled(node.parent);
    }
    return false;
  }

  // if (data.key === menu.data.value?.key) {
  //   return true;
  // }
  // if (node?.parent) {
  //   console.log(node.parent);
  //   // return node.parent.data.key === menu.data.value?.key;
  // }

  const disabled = getDisabled(node);
  // console.log(
  //   '🚀 ~ file: [key].vue:177 ~ propsDisabled ~ disabled:',
  //   data.key,
  //   disabled,
  // );

  // (data, node) => data.key === menu.data.value.key;
  return disabled;
}

// const menus = useFetchApi('/system/menu', {
//   // key: 'get-system-menu',
//   key: 'get-system-menu',
//   query: {
//     // status: Status.enable,
//   },
//   default: () => <Menu[]>[],
// });

// console.log(useFetch);
</script>

<style scoped lang="scss"></style>
